<?php

namespace QiniuUpload;

use Qiniu\Config;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use think\Exception;
use Qiniu\Processing\PersistentFop;

class QiNiuUpload
{
    private $accessKey;
    private $secretKey;
    private $bucket;
    private $auth;
    private $domain;

    public function __construct()
    {
        $this->accessKey = config('qiniu.accessKey');
        $this->secretKey = config('qiniu.secretKey');
        $this->bucket = config('qiniu.bucket');
        $this->domain = config('qiniu.domain');
        $this->auth = new Auth($this->accessKey,$this->secretKey);
	}
    
	
	/*
	 * @get uoload Token
	 */

    public function uptoken()
    {
         $token = $this->auth->uploadToken($this->bucket);
         return $token;
	}

	/*
	 * @param $name String input name value
	 * 获取上传文件链接
	 */

    private function getFileInfo($name)
    {
        $file = request()->file($name);
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        //文件后缀名
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        $token = $this->auth->uploadToken($this->bucket);
        $key = time().uniqid().'.'.$ext;
        $upManager = new UploadManager();
        $res = $upManager->putFile($token, $key, $filePath);
        //拼装图片链接
        return $this->domain.'/'.$res[0]['key'];
	}
	/*
	 *
	 * @return String images url
	 */
    public function uploadPic($name)
    {
        return ['origin'=>$this->getFileInfo($name),'tag'=>1];
	}

    public function uploadThumb($name,$width,$height)
    {
        if(!$width && !$height){
            throw  new Exception('没有指定宽高');
        }
        //获取文件名
        $key = basename($this->getFileInfo($name));
        //要进行缩略的操作。
        $fops = 'imageView2/2/w/'.$width.'/h/'.$height;
        //加密
        $saveas_key = $this->urlsafe_base64_encode($this->bucket.':'.'thumb_'.basename($key));
        $fops = $fops.'|saveas/'.$saveas_key;
        $pfop = new PersistentFop($this->auth);
        //执行
        $res = $pfop->execute($this->bucket,$key,$fops);
        //查询队列，忽略掉
//        $res = file_get_contents('https://api.qiniu.com/status/get/prefop?id='.$res[0]);
        $arr['origin'] = $this->domain.'/'.$key;
        $arr['thumb'] = $this->domain.'/'.'thumb_'.basename($key);
        $arr['tag'] = 1;
        return $arr;
	}

    //urlsafe_base64_encode函数
    private function urlsafe_base64_encode($data) {
        $data = base64_encode($data);
        $data = str_replace(array('+','/'),array('-','_'),$data);
        return $data;
    }

    //删除空间中的文件
    public function deleteFile($url)
    {
        $key = pathinfo($url)['filename'];
        $config  = new Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($this->auth,$config);
        $err = $bucketManager->delete($this->bucket, $key);
        return $err;    //很纳闷，这个返回null的时候代表删除成功
    }

    /*
     * 原始路径上传方法
     * @filePath    string  文件路径,示例：uploads/qrcode/01.jpg
     * @type        boole   文件名是否随机生成，默认为true，false则采用默认文件名保存
     * @return      string  七牛图片路径,例如:http://p8jp8dv93.bkt.clouddn.com/table_1.jpg.jpg
     */
    public function localUpload($filePath,$type = true)
    {
        //获取文件信息
        $info = pathinfo($filePath);
        //拼接：绝对路径/文件相对路径/文件名称
        $trueFileName = $_SERVER['DOCUMENT_ROOT'].'/'.$info['dirname'].'/'.$info['basename'];
        $token = $this->auth->uploadToken($this->bucket);
        if($type) {
            $key = time().uniqid().'.'.$info['extension'];
        }else{
            $key = $info['basename'].'.'.$info['extension'];
        }
        $upManager = new UploadManager();
        $res = $upManager->putFile($token, $key, $trueFileName);
        //拼装图片链接
        return $this->domain.'/'.$res[0]['key'];
    }
}